﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.Diagnostics;
using Microsoft.SharePoint.WebControls;

namespace Macaw.Wss4.GoogleAnalyticsSolution.GoogleAnalyticsTrackingCode
{
    /// <summary>
    /// This ServerControl will load the Google Analytics Tracking Code
    /// In the Master Page the following DelegateControl must be placed before the closing of the Body Tag: 
    /// <SharePoint:DelegateControl runat="server" ControlId="GoogleAnalyticsTrackingCode" AllowMultipleControls="false"/>
    /// DelegateControls are not supported from within Sandboxed Solutions
    /// </summary>
    [ToolboxData("<{0}:GoogleAnalyticsTrackingCodeControl runat=server></{0}:GoogleAnalyticsTrackingCodeControl>")]
    public class GoogleAnalyticsTrackingCodeControl : Control
    {
        /// <summary>
        /// The default Tracker code
        /// </summary>
        public string TrackerCode { get; set; }

        /// <summary>
        /// The default setting wether the authenticated users should be tracked.
        /// </summary>
        public bool TrackAuthenticated { get; set; }

        /// <summary>
        /// The default setting wether the edit mode should be tracked.
        /// </summary>
        public bool TrackEditMode { get; set; }

        protected override void CreateChildControls()
        {
            try
            {
                string code = TrackerCode;
                bool editmode = TrackEditMode;
                bool authenticated = TrackAuthenticated;

                SPSite site = SPContext.Current.Site;
                SPWeb web = SPContext.Current.Web;
                SPFile file = SPContext.Current.File;

                if (site != null && web != null && file!=null)
                {
                    bool? em = GoogleAnalyticsHelper.GetTrackEditMode(site, file, site.Zone, true);
                    if (em.HasValue)
                    {
                        editmode = em.Value;
                    }

                    bool? au = GoogleAnalyticsHelper.GetTrackAuthenticated(site, file, site.Zone, true);
                    if (au.HasValue)
                    {
                        authenticated = au.Value;
                    }

                    string pc = GoogleAnalyticsHelper.GetTrackerCode(site, file, site.Zone, true);

                    // Only use the found trackercode if it's disabled (empty string) or has a value.
                    if (pc != null) code = pc;

                }

                if (SPContext.Current.FormContext.FormMode != Microsoft.SharePoint.WebControls.SPControlMode.Display && !editmode)
                {
#if DEBUG
                    Literal message = new Literal();
                    Controls.Add(message);
                    message.Text = string.Format("<!-- Google Analytics Tracking is disabled for this page. Reason: In edit-mode-->");
#endif
                    return;
                }

                if (web.CurrentUser != null && !authenticated)
                {
#if DEBUG
                    Literal message = new Literal();
                    Controls.Add(message);
                    message.Text = string.Format("<!-- Google Analytics Tracking is disabled for this page. Reason: Authenticated user -->");
#endif
                    return;
                }

                if (!string.IsNullOrEmpty(code))
                {
                    Literal initscript = new Literal();
                    Controls.Add(initscript);
                    initscript.Text = string.Format("<script language=\"javascript\" type=\"text/javascript\">var gaJsHost = ((\"https:\" == document.location.protocol) ? \"https://ssl.\" : \"http://www.\");document.write(unescape(\"%3Cscript src='\" + gaJsHost + \"google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E\"));</script><script type=\"text/javascript\">try{{var pageTracker = _gat._getTracker(\"{0}\");pageTracker._trackPageview();}} catch(err) {{}}</script>", code);
                }
                else
                {
#if DEBUG
                    Literal message = new Literal();
                    Controls.Add(message);
                    message.Text = string.Format("<!-- Google Analytics Tracking is disabled for this page. Reason: No code defined -->");
#endif
                }
                base.CreateChildControls();
            }
            catch (Exception ex)
            {
                SPDiagnosticsService ds = SPDiagnosticsService.Local;
                ds.WriteTrace(0,
                    new SPDiagnosticsCategory("GoogleAnalyticsSolution", TraceSeverity.Monitorable, EventSeverity.Warning),
                    TraceSeverity.Medium, "Failed to inject script\r\n{0}",
                    new object[] { ex.ToString() });
            }
        }

    }
}
